"use strict";

/*************************************************************
BACKEND SCRIPTS INDEX

COLOR WIDGET AREAS
RESET SETTINGS
HELP TOGGLE
UPLOAD SCRIPT
COLORPICKER
SOCIAL LINKS CONTROL
SOCIAL LINKS PREVIEW ICON
QUOTES CONTROL
FEATURES CONTROL
SKIN PICKER
OPTION RELATIONSHIP SWITCHES
EXPORT/IMPORT SETTINGS
FONT AWESOME SELECT PREVIEW
HOMEPAGE OPTIONS SWITCHER
GOOGLE WEBFONTS
OPTIONS TABS

*************************************************************/



/*************************************************************
COLOR WIDGET AREAS
*************************************************************/

	jQuery(document).ready(function($) {
		if ($('.widget').size() > 0) {

			//color theme sidebar widget areas
			$('#canon_blog_sidebar_widget_area, #canon_page_sidebar_widget_area, #canon_404_sidebar_widget_area, #canon_contact_sidebar_widget_area').closest('.widgets-holder-wrap').children('.sidebar-name').children('h3').css({
				'backgroundColor': '#ff6666',
				'color': 'black',
				'text-shadow': 'none'
			});

			//color theme footer widget areas
			$('#canon_footer_widget_area_1, #canon_footer_widget_area_2, #canon_footer_widget_area_3, #canon_footer_widget_area_4, #canon_footer_widget_area_5').closest('.widgets-holder-wrap').children('.sidebar-name').children('h3').css({
				'backgroundColor': '#ffc000',
				'color': 'black',
				'text-shadow': 'none'
			});

			//color theme widgets (this overwrites widget colors in plugin)
			$('.widget').each(function(index, e) {
				var $this = $(this);
				if ($this.attr('id')) {
					if ($this.attr('id').indexOf('kodax_') != -1) $this.find('.widget-title').css({
						'backgroundColor': '#ff6666',
						'color': 'black',
						'text-shadow': 'none'
					});
				}

			});

			//color woocommerce widget area
			$('#canon_woocommerce_widget_area').closest('.widgets-holder-wrap').children('.sidebar-name').children('h3').css({
				'backgroundColor': '#ad74a2',
				'color': 'black',
				'text-shadow': 'none'
			});

			//color woocommerce widgets
			$('.widget').each(function(index, e) {
				var $this = $(this);
				var widgetName = $this.find('.widget-title h4').text();
				if ($this.attr('id')) {
					if (widgetName.indexOf('WooCommerce') != -1) $this.find('.widget-title').css({
						'backgroundColor': '#ad74a2',
						'color': 'black',
						'text-shadow': 'none'
					});
				}

			});


		}
	});


/*************************************************************
RESET SETTINGS
*************************************************************/

	jQuery(document).ready(function($) {
		if ($('#reset_all_button').size() > 0) {

			$('#reset_all_button').on('click', function() {
				var conf = confirm("WARNING: You are about to reset all theme settings! \n\nIf you are resetting to initialize a new theme update remember that you have the option to export your old settings before resetting. That way you can easily import them again after resetting the theme.");
				if (conf === true) {
					$('#reset_all').val('RESET');
				}
			});

		}
	});

/*****************************************
HELP TOGGLE
*****************************************/

	jQuery(document).ready(function($) {
		if ($('h3 img').size() > 0) {

			//main help toggle
			$('h3 img').on('click', function(index, e) {
				var $this = $(this);
				var $helpDiv = $this.closest('h3').next('div');
				$helpDiv.slideToggle('fast');
			});

		}
	});


/*****************************************
UPLOAD SCRIPT
*****************************************/

	//if you make an input type='button' with the class='upload_button' then this script will activate it and put the image URL in the previous input box
	jQuery(document).ready(function($) {
		if ($('.upload_button').size() > 0) {

			$(document).on('click', '.upload_button', function () {
				var $this = $(this);
				var $urlField = $this.prev('input');
				var buttonVal = $this.val().toUpperCase();

		        tb_show(buttonVal, 'media-upload.php?referer=boost_default&type=image&TB_iframe=true&post_id=0', false);
		        
				window.send_to_editor = function(html) {
					if (typeof $urlField != "undefined") {
					    var image_url = $('img',html).attr('src');  
					   	$urlField.val(image_url); 
					    tb_remove();  
					}
				};
			});

		}
	});


/*****************************************
COLORPICKER
*****************************************/

	jQuery(document).ready(function($) {

		if ($('.colorSelectorBox').size() > 0) {

			$('.colorSelectorBox').each(function (index, e) {
				var $this = $(this);
				var $relatedInput = $this.closest('td').prev('td').children('input');
				$this.ColorPicker({
					color: $relatedInput.val(),
					onShow: function (colpkr) {
						$(colpkr).fadeIn(500);
						return false;
					},
					onHide: function (colpkr) {
						$(colpkr).fadeOut(500);
						return false;
					},
					onChange: function (hsb, hex, rgb) {
						$this.find('div').css('backgroundColor', '#' + hex);
						$relatedInput.val("#" + hex);
						// console.log(rgb.b);
					}
				});
					
			});

		}	
	});

/*****************************************
SOCIAL LINKS CONTROL
*****************************************/

	jQuery(document).ready(function($) {
		if ($('.social_links').size() > 0) {

			$('.button_add_social_link').on('click', function(event) {
				var $this = $(this);
				var $socialLinksRows = $this.closest('.social_links_control').prev('.social_links').find('.social_links_row');
				var numLinks = $socialLinksRows.size();

				$socialLinksRows.last().clone().appendTo($this.closest('.social_links_control').prev('.social_links'));

				var $newRow = $this.closest('.social_links_control').prev('.social_links').find('.social_links_row').last();
				var newTitle = "Social link "+(numLinks+1);
				var newNameIcon = "canon_options[social_links]["+numLinks+"][0]";
				var newNameLink = "canon_options[social_links]["+numLinks+"][1]";

				//update indexes
				$newRow.find('th').html(newTitle);
				$newRow.find('.social_links_icon').attr('name', newNameIcon);
				$newRow.find('.social_links_link').attr('name', newNameLink);
				$newRow.find('.social_links_link').attr('value', '');

			});

			$('.button_remove_social_link').on('click', function(event) {
				var $this = $(this);
				var $socialLinksRows =  $this.closest('.social_links_control').prev('.social_links').find('.social_links_row');
				var numLinks = $socialLinksRows.size();

				if (numLinks > 1) {
					$socialLinksRows.last().remove();	
				}
			});

		}


	});


/*****************************************
SOCIAL LINKS PREVIEW ICON
*****************************************/

	jQuery(document).ready(function($) {
		if ($('.social_links').size() > 0) {

			$('.social_links').on('change', '.social_links_icon', function(event) {
				var $this = $(this);
				var thisValue = $this.val();
				thisValue = "fa " + thisValue;
				var $socialLinksRow = $this.closest('.social_links_row');
				var $iconPreview = $socialLinksRow.find('i');

				$iconPreview.attr('class', thisValue);
			});

		}

	});



/*****************************************
QUOTES CONTROL
*****************************************/

	jQuery(document).ready(function($) {
		if ($('#hp_quotes').size() > 0) {

			$('#button_add_quote').on('click', function(event) {
				var $this = $(this);
				var $quotesRows = $('#hp_quotes .hp_quotes_row');
				var numRows = $quotesRows.size();

				$quotesRows.last().clone().appendTo('#hp_quotes');

				var $newRow = $('#hp_quotes .hp_quotes_row').last();
				var newTitle = "Quote "+(numRows+1);
				var newNameQuote = "canon_options_hp[hp_quotes]["+numRows+"][0]";
				var newNameBy = "canon_options_hp[hp_quotes]["+numRows+"][1]";

				//update indexes
				$newRow.find('th').html(newTitle);
				$newRow.find('#hp_quotes_quote').attr('name', newNameQuote);
				$newRow.find('#hp_quotes_quote').attr('value', '');
				$newRow.find('#hp_quotes_by').attr('name', newNameBy);
				$newRow.find('#hp_quotes_by').attr('value', '');


			});

			$('#button_remove_quote').on('click', function(event) {
				var $this = $(this);
				var $quotesRows = $('#hp_quotes .hp_quotes_row');
				var numRows = $quotesRows.size();

				if (numRows > 1) {
					$quotesRows.last().remove();	
				}
			});

		}

	});

/*****************************************
FEATURES CONTROL
*****************************************/

	jQuery(document).ready(function($) {
		if ($('#hp_features').size() > 0) {

			$('#button_add_feature_row').on('click', function(event) {
				var $this = $(this);
				var $featureRows = $('#hp_features .hp_features_row');

				$featureRows.last().clone().appendTo('#hp_features');
				
				var numRows = $featureRows.size();
				var $newRow = $('#hp_features .hp_features_row').last();
				var $newTds	= $newRow.find('td');
				
				var newNameShow ="";
				var newNameIconUrl = "";
				var newNameTitle = "";
				var newNameText = "";


				$newTds.each(function(index) {
					var $this = $(this);
					var newNameShow = "canon_options_hp[features]["+numRows+"]["+index+"][show]";
					var newNameFontAwesomeIcon = "canon_options_hp[features]["+numRows+"]["+index+"][font_awesome_icon]";
					var newNameIconUrl = "canon_options_hp[features]["+numRows+"]["+index+"][icon_url]";
					var newNameTitle = "canon_options_hp[features]["+numRows+"]["+index+"][title]";
					var newNameText = "canon_options_hp[features]["+numRows+"]["+index+"][text]";

					//update indexes
					$this.find('.hp_features_show_hidden').attr('name', newNameShow);
					$this.find('.hp_features_show').attr('name', newNameShow);
					$this.find('.font_awesome_select').attr('name', newNameFontAwesomeIcon);
					$this.find('.hp_features_icon_url').attr('name', newNameIconUrl);
					$this.find('.hp_features_title').attr('name', newNameTitle);
					$this.find('.hp_features_text').attr('name', newNameText);

				});

			});

			$('#button_remove_feature_row').on('click', function(event) {
				var $this = $(this);
				var $featureRows = $('#hp_features .hp_features_row');
				var numRows = $featureRows.size();

				if (numRows > 1) {
					$featureRows.last().remove();	
				}
			});

		}

	});


/*************************************************************
SKIN PICKER
*************************************************************/

jQuery(document).ready(function($) {
	if ($('#skins img').size() > 0) {

		$('#skins img').on('click', function (event) {
			var $this = $(this);

			var $dataObject = $this.data();

			$.each($dataObject, function (key, value) {
				$('#'+key).val(value);
				$('#colorSelector_'+key).find('div').css('background-color',value);
			});
		});

	}

});

/*************************************************************
OPTION RELATIONSHIP SWITCHES
*************************************************************/

	jQuery(document).ready(function($) {

		if ($('.option_child').size() > 0) {

			//first hide all option children
			$('.option_child').hide();

			//now show only relevant children
			var $optionParents = $('.option_parent');

			var parentID = "";
			var newValue = "";

			$optionParents.each(function(index) {
				var $this = $(this);
				parentID = $this.attr('id');
				var parentCurrentValue = $this.attr('data-option_current_value');
				var $relevantChildren = $('.option_child[data-option_parent="'+parentID+'"][data-option_value="'+parentCurrentValue+'"]');
				$relevantChildren.show();
			});

			//on change
			$optionParents.on('change', function () {
				var $this = $(this);

				parentID = $this.attr('id');
				var $allChildren = $('.option_child[data-option_parent="'+parentID+'"]');

				//first update current value
				newValue = $this.val();
				$this.attr('data-option_current_value', newValue);

				//then hide all option children
				$allChildren.fadeOut('300');

				//now show relevant children
				var $relevantChildren = $('.option_child[data-option_parent="'+parentID+'"][data-option_value="'+newValue+'"]');
				$relevantChildren.fadeIn('300');

			});

		}

	});


/*************************************************************
EXPORT/IMPORT SETTINGS
*************************************************************/


	jQuery(document).ready(function($) {

		if ($('#canon_options_data').size() > 0) {

			//AUTOGENERATE DATA BUTTON
			$('#button_generate_data').on('click',function(e) {
				var $this = $(this);
				var optionsData = $this.attr('data-options_data');
				$this.closest('.form-table').find('#canon_options_data').html("").html(optionsData);
			});

			//SELECT ALL ON FOCUS
			$('#canon_options_data').on('focus', function (e) {
				var $this = $(this);
				$this.select();

				// Work around Chrome's little problem
				$this.mouseup(function() {
					// Prevent further mouseup intervention
					$this.unbind("mouseup");
					return false;
				});

			});


			//IMPORT DATA BUTTON
			$('#button_import_data').on('click', function(e) {
				var $this = $(this);

				var conf = confirm("WARNING: You are about to import new settings. \nOld settings may be overwritten!");
				if (conf === true) {
					$('#import_data').val('IMPORT');
				}
			});



		}


	});


/*************************************************************
FONT AWESOME SELECT PREVIEW
*************************************************************/


	jQuery(document).ready(function($) {

		if ($('.font_awesome_select').size() > 0) {

			$('body').on('change', '.font_awesome_select', function (event) {
				var $this = $(this);
				var value = $this.val();
				value = "fawesome fa " + value;
				var previewTagSelector = 'i';
				$this.next(previewTagSelector).removeClass().addClass(value);
			});
		}
		
	});




/*************************************************************
HOMEPAGE OPTIONS SWITCHER
*************************************************************/


	jQuery(document).ready(function($) {
		if ($('.options_wrapper.canon_options_homepage').size() > 0) {

			var useThemeHomepage = $('.options_wrapper.canon_options_homepage').attr('data-use_theme_homepage');
			var $defaultBlogOptions = $('.options_container_default_blog');
			var $themeHomepageOptions = $('.options_container_theme_homepage');

			if (useThemeHomepage == "true")	{
				$defaultBlogOptions.hide();		
			} else {
				$themeHomepageOptions.hide();	
			}
		}	
	});


/*****************************************
GOOGLE WEBFONTS
*****************************************/

	jQuery(document).ready(function($) {

		if ($('.canon_webfonts_controller').size() > 0) {
		
			if (typeof extDataFonts != 'undefined') {

				// console.log(extDataFonts.fonts.items[0].family);

				$('.canon_webfonts_controller').each(function(index, e) {
					//GET VARS        
					var $thisController = $(this);
					var $selectFamily = $thisController.find('.canon_font_family');
					var $selectVariant = $thisController.find('.canon_font_variant');
					var $selectSubset = $thisController.find('.canon_font_subset');
					var selectedFamily = $selectFamily.attr('data-selected');
					var selectedVariant = $selectVariant.attr('data-selected');
					var selectedSubset = $selectSubset.attr('data-selected');
					var selectedKey = 0;

					/*****************************************
					BUILD SELECTS
					*****************************************/
					//BUILD FAMILY SELECT
					for (var i = 0; i < extDataFonts.fonts.items.length; i++) {
						if (extDataFonts.fonts.items[i].family == selectedFamily) {
						var optionFamilyHTML = "<option value='"+ extDataFonts.fonts.items[i].family +"' selected='selected'>"+ extDataFonts.fonts.items[i].family +"</option>";
						selectedKey = i;
						} else {
						var optionFamilyHTML = "<option value='"+ extDataFonts.fonts.items[i].family +"'>"+ extDataFonts.fonts.items[i].family +"</option>";
						}
						$selectFamily.append(optionFamilyHTML);
					}

					//clear out select
					$selectVariant.empty();
					$selectSubset.empty();

					//build variants select
					for (var i = 0; i < extDataFonts.fonts.items[selectedKey].variants.length; i++) {
						if (extDataFonts.fonts.items[selectedKey].variants[i] == selectedVariant) {
						var optionVariantHTML = "<option value='"+ extDataFonts.fonts.items[selectedKey].variants[i] +"' selected='selected'>"+ extDataFonts.fonts.items[selectedKey].variants[i] +"</option>";
						} else {
						var optionVariantHTML = "<option value='"+ extDataFonts.fonts.items[selectedKey].variants[i] +"'>"+ extDataFonts.fonts.items[selectedKey].variants[i] +"</option>";
						}
						$selectVariant.append(optionVariantHTML);
					}

					//build subsets select
					for (var i = 0; i < extDataFonts.fonts.items[selectedKey].subsets.length; i++) {
						if (extDataFonts.fonts.items[selectedKey].subsets[i] == selectedSubset) {
						var optionSubsetHTML = "<option value='"+ extDataFonts.fonts.items[selectedKey].subsets[i] +"' selected='selected'>"+ extDataFonts.fonts.items[selectedKey].subsets[i] +"</option>";
						} else {
						var optionSubsetHTML = "<option value='"+ extDataFonts.fonts.items[selectedKey].subsets[i] +"'>"+ extDataFonts.fonts.items[selectedKey].subsets[i] +"</option>";
						}
						$selectSubset.append(optionSubsetHTML);
					}


					/*****************************************
					ON CHANGE
					*****************************************/
					//ON FAMILY CHANGE EVENT
					$selectFamily.on('change', function () {
					    var $thisFamilySelect = $(this);
					    var $relatedVariantSelect = $thisFamilySelect.closest('tr').find('.canon_font_variant');
					    var $relatedSubsetSelect = $thisFamilySelect.closest('tr').find('.canon_font_subset');
					    var selectedOption = $thisFamilySelect.val();
					    var currentKey = 0;
					    //first get the array key
					    for (var i = 0; i < extDataFonts.fonts.items.length; i++) {
							if (extDataFonts.fonts.items[i].family == selectedOption) currentKey = i;
					    }

					    //clear out select
					    $relatedVariantSelect.empty();
					    $relatedSubsetSelect.empty();

					    //build variants select
					    for (var i = 0; i < extDataFonts.fonts.items[currentKey].variants.length; i++) {
							if (extDataFonts.fonts.items[currentKey].variants[i] == selectedVariant) {
							var optionVariantHTML = "<option value='"+ extDataFonts.fonts.items[currentKey].variants[i] +"' selected='selected'>"+ extDataFonts.fonts.items[currentKey].variants[i] +"</option>";
							} else {
							var optionVariantHTML = "<option value='"+ extDataFonts.fonts.items[currentKey].variants[i] +"'>"+ extDataFonts.fonts.items[currentKey].variants[i] +"</option>";
							}
							$relatedVariantSelect.append(optionVariantHTML);
					    }

					    //build subsets select
					    for (var i = 0; i < extDataFonts.fonts.items[currentKey].subsets.length; i++) {
							if (extDataFonts.fonts.items[currentKey].subsets[i] == selectedSubset) {
							var optionSubsetHTML = "<option value='"+ extDataFonts.fonts.items[currentKey].subsets[i] +"' selected='selected'>"+ extDataFonts.fonts.items[currentKey].subsets[i] +"</option>";
							} else {
							var optionSubsetHTML = "<option value='"+ extDataFonts.fonts.items[currentKey].subsets[i] +"'>"+ extDataFonts.fonts.items[currentKey].subsets[i] +"</option>";
							}
							$relatedSubsetSelect.append(optionSubsetHTML);
					    }
					});
				});
			}

		}		

	});

/*************************************************************
OPTIONS TABS
*************************************************************/

	jQuery(document).ready(function($) {
		if ($('.settings_tab').size() > 0) {

			//init
			var currentTab = $('#show_tab').val();
			$('.tab_section').hide();
			$('.tab_section.'+currentTab).show();

			$('.settings_tab').removeClass('current_tab');
			$('.settings_tab.'+currentTab).addClass('current_tab');

			//onClick
			$('.settings_tab').on('click', function(event) {
				var $this=$(this);

				var selectedTab = $this.attr('data-tab');

				//update hidden input
				$('#show_tab').val(selectedTab);

				//update tabs
				$('.settings_tab').removeClass('current_tab');
				$('.settings_tab.'+selectedTab).addClass('current_tab');

				//update sections
				$('.tab_section').hide();
				$('.tab_section.'+selectedTab).show();

			});
		}

	});

